package com.oxygen.util;

import java.util.List;

public class CompareVersionUtil {

	public static int compare(String s1, String s2) {
		if (s1 == null && s2 == null)
			return 0;
		else if (s1 == null)
			return -1;
		else if (s2 == null)
			return 1;

		String[] arr1 = s1.split("[^a-zA-Z0-9]+"), arr2 = s2.split("[^a-zA-Z0-9]+");

		int i1, i2, i3;

		for (int ii = 0, max = Math.min(arr1.length, arr2.length); ii <= max; ii++) {
			if (ii == arr1.length)
				return ii == arr2.length ? 0 : -1;
			else if (ii == arr2.length)
				return 1;

			try {
				i1 = Integer.parseInt(arr1[ii]);
			} catch (Exception x) {
				i1 = Integer.MAX_VALUE;
			}

			try {
				i2 = Integer.parseInt(arr2[ii]);
			} catch (Exception x) {
				i2 = Integer.MAX_VALUE;
			}

			if (i1 != i2) {
				return i1 - i2;
			}

			i3 = arr1[ii].compareTo(arr2[ii]);

			if (i3 != 0)
				return i3;
		}
		return 0;
	}

	public static void main(String[] args) {
		System.out.println(CompareVersionUtil.compare("8.1.1.1", "8.1.1"));
	}

	/**
	 * 判断是否为最新版本方法 将版本号根据.切分为int数组 比较
	 * 
	 * @param localVersion
	 *            本地版本号
	 * @param onlineVersion
	 *            线上版本号
	 * @return
	 */
	public static boolean isNewVersion(String localVersion, String onlineVersion) {
		if (localVersion.equals(onlineVersion)) {
			return false;
		}
		String[] localArray = localVersion.split("\\.");
		String[] onlineArray = onlineVersion.split("\\.");

		int length = localArray.length < onlineArray.length ? localArray.length : onlineArray.length;

		try {
			for (int i = 0; i < length; i++) {
				if (Integer.parseInt(onlineArray[i]) > Integer.parseInt(localArray[i])) {
					return true;
				} else if (Integer.parseInt(onlineArray[i]) < Integer.parseInt(localArray[i])) {
					return false;
				}
				// 相等 比较下一组值
			}
		} catch (Exception e) {
			return false;
		}

		return true;
	}

	public static String findMaxVersion(String localVersion, List<String> versionList) {
		String maxVersionName = localVersion;
		for (String versionName : versionList) {
			boolean isAppNewVersion = isNewVersion(localVersion, versionName);
			// System.out.println(isAppNewVersion);
			if (isAppNewVersion) {
				isAppNewVersion = isNewVersion(maxVersionName, versionName);
				if (isAppNewVersion) {
					maxVersionName = versionName;
				}
			}
		}
		if (localVersion.equals(maxVersionName)) {
			return null;
		}
		return maxVersionName;
	}
}
